<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="search_data.name" placeholder="请输入名字" style="width: 400px;" class="filter-item" @keyup.enter.native="onSeach" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="onSeach">搜索</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleEdit()">添加</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :data="filterData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        align="center"
        width="50"
      />
      <el-table-column label="活动名称" prop="groupName" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.groupName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="原本价格" prop="price" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="活动价格" prop="sale" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sale }}</span>
        </template>
      </el-table-column>

      <el-table-column label="包含商品" prop="createDate" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.goods | returnGoods }}</span>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="280"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <el-row>
      <el-col :span="24">
        <div class="pagination">
          <el-pagination
            v-if="paginations.total > 0"
            :page-size="paginations.page_size"
            :layout="paginations.layout"
            :total="paginations.total"
            :current-page.sync="paginations.page_index"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 弹框页面 修改信息-->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      center
    >

      <div class="form">
        <el-form
          ref="form"
          :model="form"
          :rules="form_rules"
          label-width="120px"
          style="margin:10px;width:auto;"
        >
          <el-form-item prop="username" label="活动名称">
            <el-input v-model="form.username" type="username" placeholder="请输入活动名称" />
          </el-form-item>
          <el-form-item prop="nickname" label="原价格">
            <el-input v-model="form.nickname" type="nickname" placeholder="请输入原价格" />
          </el-form-item>

          <el-form-item prop="phone" label="活动价格">
            <el-input v-model="form.phone" type="phone" placeholder="请输入活动价格" />
          </el-form-item>
          <el-form-item label="包含商品">
            <el-select v-model="form.areaId" filterable placeholder="请选择">
              <el-option
                v-for="item in depList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="enabled">
            <el-radio-group v-model="form.enabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>

          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitUser('form')">提 交</el-button>
      </span>

    </el-dialog>

  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getUserList, saveUser, delUser } from '@/api/user'
export default {
  filters: { // 局部过滤器
    returnGoods: (s) => {
      let str = ''
      if (s && s.length > 0) {
        s.forEach((d, i) => {
          let sp = ','
          if (i === s.length - 1) {
            sp = ''
          }
          str += d.name + sp
        })
      }
      return str
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('负责人手机号不可为空'))
      } else {
        if (value !== '') {
          const reg = /^1[3456789]\d{9}$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的手机号码'))
          }
        }
        callback()
      }
    }
    return {
      listLoading: false,
      tableKey: 0,
      paginations: {
        page_index: 1, // 当前位于哪页
        total: 0, // 总数
        page_size: 10, // 1页显示多少条
        layout: 'total,prev, pager, next '// 翻页属性
      },
      dialog: {
        show: false,
        title: '',
        option: 'edit'
      },
      filterData: [],
      tableAll: [],
      search_data: { name: '' },
      form: {},
      form_rules: {},
      goodsList: [
        {
          'id': 1,
          'name': '电动牙刷'
        }, {
          'id': 2,
          'name': '牙膏'
        }, {
          'id': 3,
          'name': '陶瓷杯（2个装）'
        },
        {
          'id': 4,
          'name': '碧浪洗衣液'
        },
        {
          'id': 5,
          'name': '亲嘴烧'
        },
        {
          'id': 6,
          'name': '乐事薯片'
        }, {
          'id': 7,
          'name': '卫龙辣条'
        }, {
          'id': 8,
          'name': '开心果'
        },
        {
          'id': 9,
          'name': '哈密瓜500g'
        },
        {
          'id': 10,
          'name': '夏威夷果'
        }, {
          'id': 11,
          'name': '西瓜子'
        }, {
          'id': 12,
          'name': '猪肉铺'
        }, {
          'id': 13,
          'name': '鸡爪'
        }, {
          'id': 14,
          'name': '鸡腿'
        }, {
          'id': 15,
          'name': '开心果'
        }
      ],
      depList: [],
      selectGoods: [],
      paginationsInner: {
        page_index: 1, // 当前位于哪页
        total: 0, // 总数
        page_size: 10, // 1页显示多少条
        layout: 'total,prev, pager, next '// 翻页属性
      },
      selectData: [],
      downloadLoading: false
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 導出excel
    exportData() {
      this.subSelectData()
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['活动名称', '原价格', '活动价格']
        const filterVal = ['groupName', 'price', 'sale']
        const list = this.selectData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    selectDataTable() {
      this.$nextTick(() => {
        this.$refs.table.clearSelection()
        if (this.selectData.length > 0) {
          this.selectData.forEach(se => {
            this.filterData.forEach((item, index) => {
              if (item.id === se.id) { // 根据id判断是否选中
                se['dataType'] = 'del'
                this.$refs.table.toggleRowSelection(this.filterData[index], true)
              }
            })
          })
          this.selectData = this.selectData.filter(item => item['dataType'] !== 'del')
        }
      })
    },
    subSelectData() {
      // 获取当前页面选中的
      const _selectData = this.$refs.table.selection
      if (_selectData.length > 0) {
        _selectData.forEach(item => {
          const obj = this.selectData.filter(exitData => exitData.id === item.id)
          if (obj.length === 0) {
            this.selectData.push(item)
          }
        })
      } else {
        // 当前页没有数据选中 判断之前当前页面是否有数据选中 如果有则删除
        if (this.filterData.length > 0 && this.selectData.length > 0) {
          this.selectData.forEach(select => {
            const remove = this.filterData.filter(item => item.id === select.id)
            if (remove.length > 0) {
              select['removeType'] = true
            }
          })
        }
        this.selectData = this.selectData.filter(se => !se.removeType)
      }
    },
    // 获取
    getList() {
      this.tableAll = [
        {
          'id': 1,
          'groupName': '洗护活动套装',
          'price': '120',
          'sale': 50,
          'goods': [
            {
              'id': 1,
              'name': '电动牙刷'
            }, {
              'id': 2,
              'name': '牙膏'
            }, {
              'id': 3,
              'name': '陶瓷杯（2个装）'
            }
          ]
        },
        {
          'id': 1,
          'groupName': '零食大礼包',
          'price': '99',
          'sale': 50,
          'goods': [
            {
              'id': 10,
              'name': '夏威夷果'
            }, {
              'id': 14,
              'name': '鸡腿'
            }, {
              'id': 12,
              'name': '猪肉铺'
            }
          ]
        }
      ]
      this.paginations.total = this.tableAll.length
      this.handleCurrentChange(this.paginations.page_index)
      /* let url = '?page=' + this.paginations.page_index + '&size=' + this.paginations.page_size
     if (this.search_data.name !== '') {
       url += '&name=' + this.search_data.name
     }*/
      /* // 通过接口获取数据
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getUserList(url).then(response => {
          this.listLoading = false
          this.filterData = response.data.content
          this.paginations.total = response.data.totalElements
          resolve()
        }).catch(error => {
          reject(error)
        })
      })*/
    },
    // 添加 弹窗
    /* onAddMoney() {
      this.dialog.title = '添加活动'
      this.dialog.option = 'add'
      this.form = {}
      this.selectGoods = []
     this.dialog.show = true
    },*/
    // 选中数据
    changeSelect(s) {
      this.selectMedia = s
    },
    // 编辑弹窗
    handleEdit(data) {
      this.dialog.title = '添加活动'
      this.dialog.option = 'add'
      this.form = {}
      if (data) {
        this.dialog.title = '编辑活动信息'
        this.dialog.option = 'edit'
        this.form = {
          'id': 1,
          'groupName': '洗护活动套装',
          'price': '120',
          'sale': 50,
          'goods': [
            {
              'id': 1,
              'name': '电动牙刷'
            },
            {
              'id': 2,
              'name': '牙膏'
            },
            {
              'id': 3,
              'name': '陶瓷杯（2个装）'
            }
          ]
        }
      }
      this.dialog.show = true
    },

    // 删除
    handleDel(data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        return new Promise((resolve, reject) => {
          delUser(data.id).then(response => {
            if (response.message == 'success') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.filterTableData.forEach((item, index) => {
                if (item.id == data.id) {
                  this.filterTableData.splice(index, 1)
                }
              })
              this.list.forEach((item, index) => {
                if (item.id == data.id) {
                  this.list.splice(index, 1)
                }
              })
              this.setPaginations()
              this.handleCurrentChange(this.paginations.page_index)
              resolve()
            } else {
              this.$message({
                type: 'success',
                message: '删除失败!'
              })
              resolve()
            }
          }).catch(error => {
            reject(error)
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索
    onSeach() { // 查找
      this.paginations.page_index = 1
      this.getList()
    },
    // 翻页
    handleCurrentChange(page) {
      // 保存当前选中
      this.subSelectData()
      this.paginations.page_index = page
      let end = this.paginations.page_index * this.paginations.page_size
      if (end > this.paginations.total) {
        end = this.paginations.total
      }
      const start = this.paginations.page_size * (this.paginations.page_index - 1)
      this.filterData = this.tableAll.filter((item, index) => {
        return index >= start && index < end
      })
      this.selectDataTable()
    },
    // 提交数据
    onSubmitUser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.$message.success('提交成功')
        }
      })
    }

  }
}

</script>

<style scoped>
  .filter-container{
    margin-bottom: 20px;
  }
  .filter-item{
    margin-right: 10px;
  }
  .fillcontain {
    width: 100%;
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .pagination {
    text-align: right;
    margin-top: 10px;
  }
  .checkbox-style{
    padding-bottom: 20px;
    padding-left: 30px;
    padding-right: 30px;
    width: 100%;
  }
  .el-status:hover{
    cursor: pointer;
  }
</style>
